package com.cnaaa.pay.util;

import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 2018/10/26 Create by 郭文梁
 * RSAUtil
 * RSA工具类，提供rsa加密解密操作
 *
 * @author 郭文梁
 * @date 2018/10/26
 */
public class RSAUtil {
    /**
     * 加密算法
     */
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * 签名算法
     *
     * @param content   签名内容
     * @param publicKey 公钥
     * @return 签名结果
     * @throws Exception 异常
     */
    public static String sign(String content, String publicKey) throws Exception {
        PublicKey key = asPublicKey(publicKey);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        cipher.update(content.getBytes());
        byte[] result = cipher.doFinal();
        return Base64Utils.encodeToString(result);
    }

    /**
     * 解密
     *
     * @param content    密文
     * @param privateKey 私钥
     * @return 解密结果
     * @throws Exception 异常
     */
    public static String decrypt(String content, String privateKey) throws Exception {
        PrivateKey key = asPrivateKey(privateKey);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] sourceBytes = Base64Utils.decodeFromString(content);
        byte[] result = cipher.doFinal(sourceBytes);
        return new String(result);
    }

    private static PrivateKey asPrivateKey(String keyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = Base64Utils.decodeFromString(keyStr);
        PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(encodedKeySpec);
    }

    private static PublicKey asPublicKey(String keyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = Base64Utils.decodeFromString(keyStr);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(x509EncodedKeySpec);
    }
}
